from src.util.Service import *


# 查询系统拥有的角色 (分页 查询角色的所有信息)
def getRoleAll(page: Page = Page(), cdn: dict = None):
    Roles = Role.getAllRole(page, cdn)
    return Roles


# 查询系统拥有的角色 (分页 查询id 角色名)
def getRoleName(page: Page = Page()):
    Roles = Role.getAllRoleName(page)
    return Roles


# 修改角色信息（角色关键字，角色名称，启用禁用状态，角色的系统属性）
def updateRole(k: dict):
    try:
        rid = k['rId']
        k = formatParam(k, ['rId', 'initBy', 'initTime', 'updateBy', 'updateTime'])
        if rid == 1 and k['status'] != '1':
            return False
        Role.updateRole(rid, k)
        return True
    except:
        return False


# 给系统添加角色
def addRole(uid: int, data: dict):
    try:
        role = {
            'status': '1',
            'initTime': datetime.utcnow(),
            'updateTime': datetime.utcnow(),
            'initBy': uid,
            'updateBy': uid,
            'name': data['name'],
            'key': data['key'],
            'sys': 'sys',
            'indexPath': data['indexPath']
        }
        return Role.addRole(role)
    except:
        return False


# 删除系统角色
def delRole(rids: list[int]):
    # 在用户角色映射表中删除 rid 的映射关系
    if 1 in rids:
        return '你不能删除编号为1的角色'
    database.transaction()
    try:
        with database.atomic():
            UserRole.delUserRoleInRid(rids)
            RoleHandle.delRoleHandleInRid(rids)
            RoleMenu.delRoleMenuInRid(rids)
            RoleButton.delRoleButtonInRid(rids)
            Role.delRoleInId(rids)
            database.commit()
    except:
        database.rollback()
        return False
    return True


# 查询角色拥有的菜单
def getMenusByRId(rid):
    m_ids = RoleMenu.getRoleMenusIds(rid)
    return Menu.getMenusInMIds(m_ids)


# 查询角色拥有的能够使用的菜单按钮 和 角色拥有的菜单上的按钮
def getMenuHandles(rid):
    tags = RoleButton.getRoleButtonAll(rid)
    m_ids = RoleMenu.getRoleMenusIds(rid)
    smh = MenuButton.getAllMenuHandleInMids(m_ids)
    return {
        'tags': tags,
        'smh': smh
    }


def getRoleMenus(rid):
    m_ids = RoleMenu.getRoleMenusIds(rid)
    tags = RoleButton.getRoleButtonAll(rid)
    return {'mids': m_ids, 'tags': tags}


# 修改角色菜单权限
def updateRoleMenus(rid: int, mids: list[int], h_tags: list[str]):
    with database.atomic() as ts:
        canAddMids = list()
        canAddHTags = list()
        try:
            RoleMenu.delRoleMenuInRid([rid])
            RoleButton.delRoleButtonInRid([rid])
            for mid in mids:
                if Menu.hasMenu(mid):
                    canAddMids.append(mid)
            for tag in h_tags:
                if MenuButton.hasMenuHandle(tag) or rid == 1:
                    canAddHTags.append(tag)
            RoleMenu.addRoleMenu(rid, canAddMids)
            RoleButton.addRoleButton(rid, canAddHTags)
            ts.commit()
        except:
            ts.rollback()
            return False
        return True


# 查询角色拥有的操作权限
def getHandleById(rid):
    return RoleHandle.getRoleHandles(rid)


# 更新角色接口
def updateRoleHandle(rid: int, h_ids: list[int]):
    canAddHIds = []
    with database.transaction() as ts:
        try:
            RoleHandle.delRoleHandleInRid([rid])
            for hid in h_ids:
                if SysHandle.hasHandle(hid):
                    canAddHIds.append(hid)
            RoleHandle.addRoleHandle(rid, canAddHIds)
            ts.commit()
        except:
            ts.rollback()
            return False
        return True
